<?php

namespace app\models;
use yii;
use yii\base\UserException;

class UserLogin extends yii\base\Model {
    const AUTO_LOGIN_SEC = 86400; // 自动登录保持天数

    static $loginedModel;

    static $_authedData = null;

    static $sessionDataPrefix = 'gm:';

    /**
     * 判断是否登录
     *
     * @access public
     * @param  bool   $tryAutoLogin
     * @return void
     */
    public static function getIsLogined($tryAutoLogin = true) {
        $session = Yii::$app->session;
        $session->open();
        if ($session->get(self::$sessionDataPrefix . 'userData', false)) {
            return true;
        }
        return $tryAutoLogin ? self::tryAutoLogin() : false;
    }

    /**
     * 获得登录信息
     *
     * @access public
     * @return void
     */
    public static function getLoginedModel() {
        if (!self::$loginedModel) {
            self::$loginedModel = (object) json_decode(Yii::$app->session->get(self::$sessionDataPrefix . 'userData'), true);
        }

        return self::$loginedModel;
    }

    /**
     * 获得登录用户的id和username的结构
     *
     * @access public
     * @return void
     */
    public static function getIDUsername() {
        return self::getLoginedModel()->name . '(' . self::getLoginedModel()->id . ')';
    }

    /**
     * 设置登录状态
     *
     * @access public
     * @param  void   $model
     * @param  int    $autoLoginSecond
     */
    public static function setIsLogined($model, $autoLoginSecond = 0) {
        $session = Yii::$app->session;
        $session->open();

        if ($autoLoginSecond > 0) {
            $autoLoginId = md5($session->getId() . \app\helpers\Extra::create_uuid('userAutoLoginKey'));
            Yii::$app->response->cookies->add(new yii\web\Cookie([
                'name'   => 'autoLoginId',
                'value'  => $autoLoginId,
                'expire' => time() + $autoLoginSecond,
            ]));
            Yii::$app->redis->setex(Yii::$app->params['AUTOLOGIN_REDIS_PATH'] . $autoLoginId, $autoLoginSecond, json_encode($model));
        }

        $session->set(self::$sessionDataPrefix . 'userData', json_encode($model));
    }

    /**
     * 从redis自动登录
     *
     * @access public
     * @param  void   $sessionID
     * @return void
     */
    public static function tryAutoLogin() {
        // 通过sessionID读取用户session.有则放入session中

        $redisData = Yii::$app->redis->get(Yii::$app->params['AUTOLOGIN_REDIS_PATH'] . Yii::$app->request->cookies->get('autoLoginId'));
        if ($redisData) {
            Yii::$app->session->set(self::$sessionDataPrefix . 'userData', $redisData);
            return true;
        }

        return false;
    }

    /**
     * 清除自动登录的redis
     *
     * @access public
     * @param  void   $sessionID
     * @return void
     */
    public static function clearAutoLogin() {
        if (Yii::$app->request->cookies->get('autoLoginId')) {
            Yii::$app->response->cookies->remove('autoLoginId');
            Yii::$app->redis->del(Yii::$app->params['AUTOLOGIN_REDIS_PATH'] . Yii::$app->request->cookies->get('autoLoginId'));
        }
    }

    /**
     * 通过code获取用户信息
     *
     * @access public
     * @param  void   $code
     * @return void
     */
    public static function checkAuth($code) {
        $curl = new \app\helpers\curl\Curl;
        $curl->post('http://' . Yii::$app->params['AUTHCENTER_DOMAIN'] . '/authcenter/api/get-user-info', [
            'code'  => $code,
            'time'  => $_SERVER['REQUEST_TIME'],
            'token' => md5($code . Yii::$app->params['AUTHCENTER_KEY'] . $_SERVER['REQUEST_TIME']),
        ]);
        $resultArr = json_decode($curl->rawResponse, true);

        if (!isset($resultArr['code']) || $resultArr['code'] != 0) {
            self::generateCode();
        }
        // var_dump($resultArr['data']);exit;
        self::setIsLogined((object) $resultArr['data'], self::AUTO_LOGIN_SEC);

        return true;
    }

    /**
     * 向用户中心重新请求登录
     *
     * @access public
     * @return void
     */
    public static function generateCode() {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
            throw new UserException(Yii::t('tip', 'Please relogin'), 1);
        }

        exit(Yii::$app->response->redirect(
            'http://' . Yii::$app->params['AUTHCENTER_DOMAIN'] . '/authcenter/api/generate-code?sys=' . Yii::$app->params['AUTHCENTER_SYSTEM_NAME'] . '&url=' . urlencode(Yii::$app->request->getAbsoluteUrl()),
            // 'http://' . Yii::$app->params['AUTHCENTER_DOMAIN'] . '/authcenter/api/generate-code?sys=' . Yii::$app->params['AUTHCENTER_SYSTEM_NAME'] . '&url=' . urlencode(Url::base(true)),
            302
        )->send());
    }

    public static function get_uid(){
        $session = Yii::$app->session;
        $userData = $session->get(self::$sessionDataPrefix . 'userData');
        $userData_arr = json_decode($userData, true);
        if ($userData_arr) {
            return $userData_arr['id'];
        }
        return 0;
        
    }
}
